<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="物流产品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name" :rules="[{ required: true, message: '请输入物流产品名称!'}]">
              <a-input v-model="model.name" placeholder="请输入物流产品名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="物流渠道" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="channelId">
              <j-search-select-tag v-model="model.channelId" dict="hz_logistics_channel,channel_name,id,logistics,is_enable='Y'" placeholder="请选择物流渠道" @change="channelIdChange" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="title_ === '编辑'">
            <a-form-model-item label="报价币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currencyType">
              <j-dict-select-tag type="list" v-model="model.currencyType" dictCode="logistics_currency_type" placeholder="请选择报价币种" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="成本价方案" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="costPriceId">
              <j-search-select-tag ref="costPriceIdRef" placeholder="请选择成本价方案" v-model="model.costPriceId" :disabled="!model.channelId" @change="getLogisticsCostPriceList" ></j-search-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="effectBeginTime">
              <j-date placeholder="请选择生效时间"  v-model="model.effectBeginTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled-date="disabledDate" :disabled-time="disabledTime" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="title_ === '编辑'">
            <a-form-model-item label="产品代码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <span>{{ model.code }}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class="table-operator">
          <a-button type="primary" @click="handleBatchCost" :disabled="!(logisticsCostPriceDetailTable.dataSource && logisticsCostPriceDetailTable.dataSource.length)">批量费用</a-button>
          <!-- 无数据禁止操作，保证成本价方案和表单一一对应 -->
          <a-button type="primary" icon="download" @click="handleExportXls('物流成本价详情模板', 'template', {costPriceId: model.costPriceId})" :disabled="!(logisticsCostPriceDetailTable.dataSource && logisticsCostPriceDetailTable.dataSource.length)">导出模板</a-button>
          <a-upload name="file" :data="{costPriceId: model.costPriceId}" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
            <a-button type="primary" icon="import" :disabled="!(logisticsCostPriceDetailTable.dataSource && logisticsCostPriceDetailTable.dataSource.length)">导入</a-button>
          </a-upload>
        </div>
        <j-editable-table
          :class="{canscroll: formDisabled}"
          :ref="refKeys[0]"
          :loading="logisticsCostPriceDetailTable.loading"
          :columns="logisticsCostPriceDetailTable.columns"
          :dataSource="logisticsCostPriceDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          @valueChange="handleValueChange"
        />
      </a-form-model>
    </j-form-container>
    <logistics-product-form-modal ref="modalForm" @ok="modalFormOk"></logistics-product-form-modal>
  </a-spin>
</template>

<script>
  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import LogisticsProductFormModal from './LogisticsProductFormModal'
  import moment from 'moment'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'

  export default {
    name: 'LogisticsProductForm',
    mixins: [JEditableTableModelMixin, JeecgListMixin],
    components: {
      LogisticsProductFormModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      title_: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          channelId: [
            { required: true, message: '请选择物流渠道!'},
          ],
          costPriceId: [
            { required: true, message: '请选择成本价方案!'},
          ],
          currencyType: [
            { required: true, message: '请选择报价币种!'},
          ],
          effectBeginTime: [
            { required: true, message: '请选择生效时间!' },
            { validator: this.validEffectBeginTime }
          ]
        },
        url: {
          add: "/logistics/product/logisticsProduct/add",
          edit: "/logistics/product/logisticsProduct/edit",
          logisticsCostPriceList: "/logistics/costPrice/logisticsCostPrice/list",
          queryHzLogisticsCostPriceDetailByMainId: "/logistics/costPrice/logisticsCostPrice/queryHzLogisticsCostPriceDetailByMainId",
          queryDetailByMainId: "/logistics/product/logisticsProduct/queryDetailByMainId",
          exportTemplateXlsUrl: "/logistics/product/hzLogisticsProductDetail/exportTemplate",
          exportXlsUrl: "/logistics/product/hzLogisticsProductDetail/exportExcel",
          importExcelUrl: "logistics/product/hzLogisticsProductDetail/importExcel",
        },
        refKeys: ['logisticsCostPriceDetail', ],
        tableKeys:['logisticsCostPriceDetail', ],
        activeKey: 'logisticsCostPriceDetail',
        logisticsCostPriceDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '收费分区',
              key: 'classifyId',
              type: FormTypes.select,
              width:"100px",
              dictCode:"hz_logistics_partition_classify,name,id,logistics",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '计费类型',
              key: 'chargeType',
              type: FormTypes.select,
              dictCode:"logistics_charge_type",
              width:"100px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '开始重量段（KG）',
              key: 'startWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '结束重量段（KG）',
              key: 'endWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '最低计费重（KG）',
              key: 'minChargeWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '',
              defaultValue:'',
              disabled: true
            },
            {
              title: '计费单重（KG）',
              key: 'chargeWeight',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            // {
            //   title: '价格值',
            //   key: 'price',
            //   type: FormTypes.inputNumber,
            //   width:"90px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            //   disabled: true
            // },
            // {
            //   title: '挂号费',
            //   key: 'registerFee',
            //   type: FormTypes.inputNumber,
            //   width:"90px",
            //   placeholder: '请输入${title}',
            //   defaultValue:'',
            //   disabled: true
            // },
            {
              title: '公斤费',
              key: 'kiloFee',
              type: FormTypes.inputNumber,
              width:"90px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, pattern: /^[0-9]+(\.[0-9]+)?$/, message: '${title}不能小于0' }]
            },
            {
              title: '处理费',
              key: 'processFee',
              type: FormTypes.inputNumber,
              width:"90px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, pattern: /^[0-9]+(\.[0-9]+)?$/, message: '${title}不能小于0'}]
            },
          ]
        },
        editProductDetails: [],
        disableMixinCreated: true,
        typeTitle_: '',
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'生效时间',
            align:"center",
            dataIndex: 'effectBeginTime',
            scopedSlots: { customRender: 'timeSlot' }
          },
          {
            title:'状态',
            align:"center",
            dataIndex: 'effectStatus_dictText',
          },
          {
            title:'创建时间',
            align:"center",
            dataIndex: 'createTime',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        lastTime: moment(),
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      test(){
        console.log(JSON.stringify(this.model));
      },
      addBefore(){
        this.logisticsCostPriceDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        if (this.model.id) {
          // 加载子表数据
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.queryDetailByMainId, params, this.logisticsCostPriceDetailTable, (res) => {
            this.editProductDetails = res.result;
          })
          // 获取成本价数据源
          this.channelIdChange('edit');
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues){
        let productDetails = [...allValues.tablesValue[0].values];
        if(this.title_ === '新增' && this.typeTitle_ != '导入'){
          //将table中的costPriceDetailId置为id，id置为null
          productDetails = productDetails.map(item => {
            if(!item.costPriceDetailId){
              return {
                ...item,
                costPriceDetailId: item.id,
                id: null
              }
            }else{
              //新增中导入的数据不用重置
              return item;
            }
          })
        }
        if(this.title_ === '编辑' || this.typeTitle_ === '导入'){
          productDetails = this.editProductDetails;
        }
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          productDetails,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      getLogisticsCostPriceList(){
        if(!(this.model.channelId && this.model.costPriceId)) return;
        this.logisticsCostPriceDetailTable.dataSource = [];
        this.editProductDetails = [];
        this.requestSubTableData(this.url.queryHzLogisticsCostPriceDetailByMainId, { id: this.model.costPriceId }, this.logisticsCostPriceDetailTable, (res) => {
          this.editProductDetails = res.result;
        })
      },
      channelIdChange(type){
        if(type != 'edit'){
          this.model.costPriceId = '';
          this.logisticsCostPriceDetailTable.dataSource = [];
          this.editProductDetails = [];
        }
        this.$refs.costPriceIdRef.setCurrentDictOptions([]);
        let params = {
          channelId: this.model.channelId,
          ableStatus: '2', //启动中
          effectStatus: '1,2', //生效前、生效中
          pageNo: 1,
          pageSize: 9999
        }
        getAction(this.url.logisticsCostPriceList, params).then((res) => {
          if(res.success){
            let dictOptions = res.result && res.result.records && res.result.records.map(item => {
              return {
                value: item.id,
                text: item.name
              }
            })
            this.$refs.costPriceIdRef.setCurrentDictOptions(dictOptions);
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleBatchCost(){
        let ref = this.refKeys[0];
        if(this.$refs[ref]){
          let currentSelection = this.$refs[ref].getSelection();
          if(!currentSelection.length){
            this.$message.warning('请选择数据!');
            return;
          }
          this.$refs.modalForm.add();
          this.$refs.modalForm.title = "批量费用设置";
          this.$refs.modalForm.disableSubmit = false;
        }
      },
      modalFormOk(model){
        let ref = this.refKeys[0];
        if(this.$refs[ref]){
          let currentSelection = this.$refs[ref].getSelection();
          this.logisticsCostPriceDetailTable.dataSource = this.editProductDetails.map(item => {
            if(currentSelection.indexOf(item.id) > -1){
              return {
                ...item,
                kiloFee: model.kiloFee,
                processFee: model.processFee
              }
            }else{
              return item;
            }
          })
          this.editProductDetails = this.editProductDetails.map(item => {
            if(currentSelection.indexOf(item.id) > -1){
              return {
                ...item,
                kiloFee: model.kiloFee,
                processFee: model.processFee
              }
            }else{
              return item;
            }
          })
        }
      },
      handleOk_(){
        this.handleOk();
      },
      disabledDate(current){
        // 禁用今天之前的日期
        return current && current < moment(this.lastTime).subtract(1, 'days').endOf('day');
      },
      disabledTime(current){
        let hourList = Array.from({ length: 24 }, (_, index) => index);
        let minutesList = Array.from({ length: 60 }, (_, index) => index);
        let secondsList = Array.from({ length: 60 }, (_, index) => index);
        // 1.选择时间晚于当前(天)
        if(moment(moment(current).format('YYYY-MM-DD')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          return {
            disabledHours: () => [],
            disabledMinutes: () => [],
            disabledSeconds: () => [],
          };
        }else if(moment(moment(current).format('YYYY-MM-DD')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          //3.编辑返参早于当前
          return {
            disabledHours: () => hourList,
            disabledMinutes: () => minutesList,
            disabledSeconds: () => secondsList,
          };
        }
        // 2.选择时间等于当前(天)
        let currentHourList = [], currentminutesList = [], currentsecondsList = [];
        if(moment(current).format('YYYY-MM-DD') === moment(this.lastTime).format('YYYY-MM-DD')){
          // 选择的时间为限制时间之后
          currentHourList = hourList.filter(item => item < moment(this.lastTime).format('HH'));
          // 2.选择时间等于当前(时)
          if(moment(current).format('YYYY-MM-DD HH') === moment(this.lastTime).format('YYYY-MM-DD HH')){
            // 选择的时间为限制时间之后
            currentminutesList = minutesList.filter(item => item < moment(this.lastTime).format('mm'));
            // 2.选择时间等于当前(分)
            if(moment(current).format('YYYY-MM-DD HH:mm') === moment(this.lastTime).format('YYYY-MM-DD HH:mm')){
              currentsecondsList = secondsList.filter(item => item < moment(this.lastTime).format('ss'));
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间晚于当前(分)
              currentsecondsList = [];
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间早于当前(分)
              currentsecondsList = secondsList;
            }
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间晚于当前(时)
            currentminutesList = [];
            currentsecondsList = [];
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间早于当前(时)
            currentminutesList = minutesList;
            currentsecondsList = secondsList;
          }
          return {
            disabledHours: () => currentHourList,
            disabledMinutes: () => currentminutesList,
            disabledSeconds: () => currentsecondsList,
          };
        }
      },
      validEffectBeginTime(rule, value, callback){
        if(!value){
          callback('请选择生效时间!');
        }else{
          if(moment(moment(value).format('YYYY-MM-DD HH:mm:ss')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm:ss')))){
            callback('生效时间需晚于最新版本时间或系统时间!');
          }else{
            callback();
          }
        }
      },
      handleValueChange({ row }){
        this.editProductDetails = this.editProductDetails.map(item => {
          if(item.id === row.id){
            return {
              ...item,
              kiloFee: row.kiloFee,
              processFee: row.processFee
            }
          }else{
            return item
          }
        })
      },
      handleImportExcel(info){
        this.loading = true;
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          this.loading = false;
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let { message, result: { msg, fileUrl, fileName } } = info.file.response
              this.$warning({
                title: message,
                content: (<div>
                    <span>{msg}</span><br/>
                    <span>具体详情请 <a href={fileUrl} target="_blank" download={fileName}>点击下载</a> </span>
                  </div>
                )
              })
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
              //更新表单
              this.logisticsCostPriceDetailTable.dataSource = info.file.response.result.dataList;
              this.editProductDetails = info.file.response.result.dataList;
              this.typeTitle_ = '导入';
            }
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.loading = false;
          if (info.file.response.status === 500) {
            let data = info.file.response
            const token = Vue.ls.get(ACCESS_TOKEN)
            if (token && data.message.includes("Token失效")) {
              this.$error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout').then(() => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    window.location.reload();
                  })
                }
              })
            }
          } else {
            this.$message.error(`文件上传失败: ${info.file.msg} `);
          }
        }
      }
    }
  }
</script>

<style scoped>
.canscroll /deep/.input-table .scroll-view{
  pointer-events: auto;
}
</style>